package cn.hznc.controller.service.program.logic;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.domain.entity.SubProgramEntity;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 子程序逻辑业务层
 *
 * @Author Administrator
 * @Date 2023/3/14 10:31
 */
public class SubProgramManageLogic {

    private final SubProgramDo subProgramDo;

    private final List<SubProgramEntity> originSubProgramList;

    private final List<SubProgramEntity> updateSubProgramList;

    public SubProgramManageLogic(List<SubProgramEntity> originSubProgramList, List<SubProgramEntity> updateSubProgramList) {
        this.originSubProgramList = originSubProgramList;
        this.updateSubProgramList = updateSubProgramList;
        this.subProgramDo=new SubProgramDo();
    }

    /**
     * 获取处理后的业务模型
     *
     * @return subProgramDo
     */
    public SubProgramDo getSubProgramDo() {
        return subProgramDo;
    }

    /**
     *
     */
    public void buildSubProgramDo(){
        if (CollectionUtil.isEmpty(originSubProgramList)){
            subProgramDo.addCreateElement(updateSubProgramList);
            return;
        }
        if (CollectionUtil.isEmpty(updateSubProgramList)){
            subProgramDo.addDeleteElement(originSubProgramList);
            return;
        }
        // 比对id判断，对删除，修改，新增
        List<Integer> ids = originSubProgramList.stream().map(SubProgramEntity::getId).collect(Collectors.toList());
        List<Integer> updateIds = updateSubProgramList.stream().filter(updateSubProgram->ObjectUtil.isNotNull(updateSubProgram.getId())).map(SubProgramEntity::getId).collect(Collectors.toList());
        for (SubProgramEntity subProgramEntity : updateSubProgramList) {
            // 添加修改元素
            if (ids.contains(subProgramEntity.getId())) {
                subProgramDo.addUpdateElement(subProgramEntity);
            }
            // 添加新增元素
            if (ObjectUtils.isEmpty(subProgramEntity.getId())){
                subProgramDo.addCreateElement(subProgramEntity);
            }
        }
        for (SubProgramEntity subProgramEntity : originSubProgramList) {
            // 添加删除元素
            if (!updateIds.contains(subProgramEntity.getId())){
                subProgramDo.addDeleteElement(subProgramEntity);
            }
        }
    }

}
